#include "../source/server.hpp"

std::unordered_map<uint64_t, PtrConnect> _conns;
uint64_t count = 0;
EventLoop loop;
LoopThreadPool *loopthread;

void OnMessage(const PtrConnect &con, Buffer *buf)
{
    DLOG("%s", buf->GetReaderPos());
    buf->ReadMoveOffset(buf->ReadAbleSize());
    std::string res = "Hello tc!";
    con->SendCon(res.c_str(), res.size());
    con->Shutdown();
}

void OnConnectDestory(const PtrConnect &con)
{
    _conns.erase(con->ID());
}

void OnConnection(const PtrConnect &con)
{
    DLOG("CONNECTION ADDRESS %p", con.get());
}

void NewConnection(int newfd)
{
    count++;
    PtrConnect con(new Connection(loopthread->GetNextEventLoop(), newfd, count)); // 获取一个从属线程
    con->SetMessageCallBack(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    con->SetServerCloseCallBack(std::bind(OnConnectDestory, std::placeholders::_1));
    con->SetConnectCallBack(std::bind(OnConnection, std::placeholders::_1));
    con->EnableInactiveRelease(10); // 启动非活跃销毁任务
    con->Establish();               // 初始化
    _conns.insert(std::make_pair(count, con));
    DLOG("New Thread -------------------------");
}

int main()
{
    loopthread = new LoopThreadPool(&loop);
    loopthread->SetSlaveThreadNumber(2);
    loopthread->CreateSlaveThreads();
    Acceptor acceptor(&loop, 8881);
    acceptor.SetAcceptCallBack(std::bind(NewConnection, std::placeholders::_1));
    acceptor.Listen();
    loop.StartEventLoop();
    return 0;
}